package com.lzs.bootsafety.common.util.http;

import com.alibaba.fastjson.JSONObject;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;

public class AddressUtil {
	/** 获取地址开关 */
	private static boolean addressEnabled = true;
	/** 空字符串 */
	private static final String NULLSTR = "";
	private static final Logger log = LoggerFactory.getLogger(AddressUtil.class);

	public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";

	public static String getRealAddressByIP(String ip) {
		String address = "XX XX";
		if (IpUtils.internalIp(ip)) {
			return "内网IP";
		}
		if (isAddressEnabled()) {
			String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip);
			if (isEmpty(rspStr)) {
				log.error("获取位置异常 {}", ip);
				return address;
			}
			JSONObject obj = JSONObject.parseObject(rspStr);
			JSONObject data = obj.getObject("data", JSONObject.class);
			String region = data.getString("region");
			String city = data.getString("city");
			address = region + " " + city;
		}
		return address;
	}
	//获取浏览器名称
	public static String getBrowserName(HttpServletRequest request) {
        String header = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(header);
        Browser browser = userAgent.getBrowser();
        return browser.getName();
	}
	//获取操作系统型号
	public static String getOsName(HttpServletRequest request) {
        String header = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(header);
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();
        return operatingSystem.getName();
    }
	public static boolean isAddressEnabled() {
		return addressEnabled;
	}

	public static boolean isEmpty(String str) {
		return isNull(str) || NULLSTR.equals(str.trim());
	}

	public static boolean isNull(Object object) {
		return object == null;
	}
}
